/* ex: set tabstop=4 shiftwidth=4 expandtab: */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/socket.h>

#include "rtsp.h"
#include "rtsp_proto.h"
#include "rtp.h"

#define SDP_RESP_HEAD \
	"RTSP/1.0 200 OK\r\n"\
	"Server: Havana/1.25\r\n"\
	"%s\r\n"\
	"Content-Type: application/sdp\r\n"\
	"Content-Base: rtsp://%s:%d/DSP/vbr=500000.vmbr=850000.vfr=30.vw=352.vh=240.vfl=0x1519.abr=48000.ambr=48000.asr=24000.afl=0x516.vtype=2./\r\n"\
	"Content-Length: %d\r\n"\
	"\r\n"\

#define SDP_RESP \
	"v=0\r\n"\
	"o=StreamingServer 23196166666 1 IN IP4 10.0.0.1\r\n"\
	"s=DSP/vbr=500000.vmbr=850000.vfr=30.vw=352.vh=240.vfl=0x1519.abr=48000.ambr=48000.asr=24000.afl=0x516.vtype=2.\r\n"\
	"c=IN IP4 0.0.0.0\r\n"\
	"i=DSP session streamed by \"netAV\"\r\n"\
	"t=0 0\r\n"\
	"a=tool:netAV\r\n"\
	"m=video 0 RTP/AVP 96\r\n"\
	"a=rtpmap:96 PSP-H264/90000\r\n"\
	"a=fmtp:96\r\n"\
	"a=control:trackID=2\r\n"\
	"m=audio 0 RTP/AVP 97\r\n"\
	"a=rtpmap:97 mpeg4-generic/24000/2\r\n"\
	"a=fmtp:97 profile-level-id=1; bitrate=48000; cpresent=0; object=2; mode=AAC-hbr; config=1310; SizeLength=13; IndexLength=3; IndexDeltaLength=3;\r\n"\
	"a=control:trackID=1\r\n"\
	"\r\n"
	
#define SETUP_RESP \
	"RTSP/1.0 200 OK\r\n"\
	"Server: Hanava/1.25\r\n"\
	"%s\r\n"\
	"%s\r\n"\
	"Session: %d\r\n"\
	"\r\n"

#define PLAY_RESP \
	"RTSP/1.0 200 OK\r\n"\
	"Server: Havana/1.25\r\n"\
	"%s\r\n"\
	"Session: %d\r\n"\
	"\r\n"

#define TEARDOWN_RESP \
	"RTSP/1.0 200 OK\r\n"\
	"Server: Havana/1.25\r\n"\
	"%s\r\n"\
	"Session: %d\r\n"\
	"\r\n"


static char *
get_line(char *req, char *head, char *buf)
{
	char *q = buf;
	char *p = strstr(req, head);

	if (!p)
		return NULL;
	while (*p != '\r')
		*q++ = *p++;
	*q = '\0';

	return buf;	
}

int
rtsp_parse_request(rtsp_session_t *sess, rtsp_channel_t *ch, char *buf)
{
	int len;
	char transport[256];
	char cseq[256];

	if (!get_line(ch->buf, "CSeq:", cseq))
		return 0;

	if (strncmp(ch->buf, "DESCRIBE", 8) == 0) {
		len = sprintf(buf, SDP_RESP_HEAD, cseq, netav_host, NETAV_PORT, strlen(SDP_RESP));
		send(sess->chn_get->fd, buf, len, 0);
		send(sess->chn_get->fd, SDP_RESP, strlen(SDP_RESP), 0);
	} else if (strncmp(ch->buf, "SETUP", 5) == 0) {
		if (!get_line(ch->buf, "Transport:", transport))
			return 0;
		len = sprintf(buf, SETUP_RESP, cseq, transport, 1);
		send(sess->chn_get->fd, buf, len, 0);
	} else if (strncmp(ch->buf, "PLAY", 4) == 0) {
		len = sprintf(buf, PLAY_RESP, cseq, 1);
		send(sess->chn_get->fd, buf, len, 0);
		rtp_start(sess);
	} else if (strncmp(ch->buf, "TEARDOWN", 8) == 0) {
		len = sprintf(buf, TEARDOWN_RESP, cseq, 1);
		send(sess->chn_get->fd, buf, len, 0);
		rtp_stop(sess);
	}

	ch->buf[0] = '\0';
	ch->len = 0;

	return 0;
}

